package com.tabbinder.server;

import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.NotPersistent;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

import org.json.JSONException;
import org.json.JSONObject;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.users.User;

/**
 * Record of attachment of Binder to a user
 * 
 * @author Tatiana Kichkaylo
 */
@PersistenceCapable(identityType = IdentityType.APPLICATION)
public class BindRecord {
	@NotPersistent
	private static Logger log = Logger.getLogger(BindRecord.class.getName());

	/** unique id for the record - we don't need it, but the data store might */
	@PrimaryKey
	@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
	private Key id;

	/** Binder id this is about */
	@Persistent
	private Binder binder;

	/** Key of the user (see docs about User and changing user email) */
	@Persistent
	private User user;

	/**
	 * Inactivity delay after which the record should be dropped (can be
	 * 'never', i.e. NULL)
	 */

	/**
	 * Time stamp of last time the binder was deactivated or NULL if the binder
	 * is opened somewhere (used with the previous field)
	 */
	@Persistent
	private Date lastTouched;

	/** Flag for whether this binder is favorite */
	@Persistent
	private boolean favorite;

	// possibly other things like creation time stamp, but not right away

	public BindRecord(Binder binder, User user) {
		this.binder = binder;
		this.user = user;
		binder.addRecord(this);
	}

	public Date getLastTouched() {
		return lastTouched;
	}

	public void setLastTouched(Date lastTouched) {
		this.lastTouched = lastTouched;
	}

	public boolean isFavorite() {
		return favorite;
	}

	public void setFavorite(boolean favorite) {
		this.favorite = favorite;
	}

	public Key getId() {
		return id;
	}

	public Binder getBinder() {
		return binder;
	}

	public User getUser() {
		return user;
	}

	/** Add fields to the given JSON object and return the changed object */
	public JSONObject addFields(JSONObject obj) {
		try {
			obj.put("favorite", favorite);
		} catch (JSONException e) {
			log.log(Level.SEVERE, "Cannot create JSON: ", e);
		}
		return obj;
	}

	/** Mostly for debugging */
	@Override
	public String toString() {
		return binder.toString() + " 4 " + user + ": " + favorite + ", "
				+ lastTouched;
	}
}
